import { useState } from 'react'
import { Card, Table, Button, Space, Tag, Modal, message, Tabs, Badge } from 'antd'
import { BellOutlined, CheckOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons'
import './index.scss'

const Notifications = () => {
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [activeTab, setActiveTab] = useState('all')

  // 模拟数据
  const [dataSource, setDataSource] = useState([
    {
      id: 1,
      type: 'audit',
      title: '待审核内容提醒',
      content: '当前有15条笔记、8条书评、23条评论待审核',
      status: 'unread',
      createTime: '2024-01-20 10:30:00',
    },
    {
      id: 2,
      type: 'report',
      title: '用户举报通知',
      content: '用户"李四"举报了一条不当评论，请及时处理',
      status: 'unread',
      createTime: '2024-01-19 15:20:00',
    },
    {
      id: 3,
      type: 'system',
      title: '系统异常告警',
      content: '服务器CPU使用率超过85%，请关注系统运行状态',
      status: 'read',
      createTime: '2024-01-18 09:15:00',
    },
    {
      id: 4,
      type: 'overdue',
      title: '图书逾期提醒',
      content: '当前有12本图书逾期未归还，最长逾期15天',
      status: 'unread',
      createTime: '2024-01-17 14:45:00',
    },
    {
      id: 5,
      type: 'user',
      title: '新用户注册',
      content: '今日新增注册用户35人，较昨日增长20%',
      status: 'read',
      createTime: '2024-01-16 11:20:00',
    },
    {
      id: 6,
      type: 'data',
      title: '数据统计报告',
      content: '本周阅读量较上周增长15%，活跃用户数增长8%',
      status: 'read',
      createTime: '2024-01-15 16:30:00',
    },
  ])

  // 类型配置
  const typeConfig = {
    audit: { text: '审核', color: 'orange', icon: '📝' },
    report: { text: '举报', color: 'red', icon: '⚠️' },
    system: { text: '系统', color: 'purple', icon: '🔔' },
    overdue: { text: '逾期', color: 'volcano', icon: '⏰' },
    user: { text: '用户', color: 'blue', icon: '👤' },
    data: { text: '数据', color: 'green', icon: '📊' },
  }

  // 标记为已读
  const handleMarkRead = (record) => {
    setDataSource(prev =>
      prev.map(item =>
        item.id === record.id ? { ...item, status: 'read' } : item
      )
    )
    message.success('已标记为已读')
  }

  // 删除通知
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定删除这条通知吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        setDataSource(prev => prev.filter(item => item.id !== record.id))
        message.success('删除成功')
      },
    })
  }

  // 批量标记已读
  const handleBatchMarkRead = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要标记的通知')
      return
    }
    setDataSource(prev =>
      prev.map(item =>
        selectedRowKeys.includes(item.id) ? { ...item, status: 'read' } : item
      )
    )
    setSelectedRowKeys([])
    message.success('批量标记已读成功')
  }

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的通知')
      return
    }
    Modal.confirm({
      title: '批量删除',
      content: `确定删除选中的 ${selectedRowKeys.length} 条通知吗？`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        setDataSource(prev => prev.filter(item => !selectedRowKeys.includes(item.id)))
        setSelectedRowKeys([])
        message.success('批量删除成功')
      },
    })
  }

  // 全部标记已读
  const handleMarkAllRead = () => {
    Modal.confirm({
      title: '全部标记已读',
      content: '确定将所有未读通知标记为已读吗？',
      onOk: () => {
        setDataSource(prev =>
          prev.map(item => ({ ...item, status: 'read' }))
        )
        message.success('全部标记已读成功')
      },
    })
  }

  // 导出数据
  const handleExport = () => {
    message.success('开始导出数据')
  }

  // 根据Tab筛选数据
  const filteredData = dataSource.filter(item => {
    if (activeTab === 'all') return true
    if (activeTab === 'unread') return item.status === 'unread'
    if (activeTab === 'read') return item.status === 'read'
    return true
  })

  // 统计各状态数量
  const getStatusCount = (status) => {
    if (status === 'all') return dataSource.length
    if (status === 'unread') return dataSource.filter(item => item.status === 'unread').length
    if (status === 'read') return dataSource.filter(item => item.status === 'read').length
    return 0
  }

  const columns = [
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => (
        <Tag color={typeConfig[type].color}>
          {typeConfig[type].icon} {typeConfig[type].text}
        </Tag>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {record.status === 'unread' && (
            <Badge status="processing" />
          )}
          <span style={{ fontWeight: record.status === 'unread' ? 600 : 400 }}>
            {text}
          </span>
        </div>
      ),
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 'unread' ? 'orange' : 'default'}>
          {status === 'unread' ? '未读' : '已读'}
        </Tag>
      ),
    },
    {
      title: '时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          {record.status === 'unread' && (
            <Button
              type="link"
              size="small"
              icon={<CheckOutlined />}
              style={{ color: '#52c41a' }}
              onClick={() => handleMarkRead(record)}
            >
              已读
            </Button>
          )}
          <Button
            type="link"
            size="small"
            icon={<DeleteOutlined />}
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  }

  return (
    <div className="notifications-container">
      <Card className="table-card">
        <div className="tabs-header">
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            className="status-tabs"
            items={[
              {
                key: 'all',
                label: `全部 (${getStatusCount('all')})`,
              },
              {
                key: 'unread',
                label: (
                  <Badge count={getStatusCount('unread')} offset={[10, 0]}>
                    <span>未读</span>
                  </Badge>
                ),
              },
              {
                key: 'read',
                label: `已读 (${getStatusCount('read')})`,
              },
            ]}
          />
          <div className="tabs-actions">
            <Space>
              <Button
                type="primary"
                icon={<CheckOutlined />}
                onClick={handleBatchMarkRead}
                disabled={selectedRowKeys.length === 0}
              >
                批量已读
              </Button>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
              >
                批量删除
              </Button>
              <Button
                icon={<BellOutlined />}
                onClick={handleMarkAllRead}
                disabled={getStatusCount('unread') === 0}
              >
                全部已读
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出数据
              </Button>
            </Space>
          </div>
        </div>

        {selectedRowKeys.length > 0 && (
          <div className="selection-bar">
            <span className="selection-info">
              已选择 {selectedRowKeys.length} 项
            </span>
          </div>
        )}

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1000 }}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
        />
      </Card>
    </div>
  )
}

export default Notifications
